package com.ggs.controller;

import com.ggs.DTO.LogUserDTO;
import com.ggs.DTO.UserDTO;
import com.ggs.pojo.User;
import com.ggs.service.UserService;
import com.ggs.utils.JwtUtils;
import com.ggs.utils.ThreadLocalUtils;
import com.ggs.vo.ResultVO;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@Validated
@RestController
@RequestMapping("/user")

public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 注册用户
    @PostMapping("/register")
    public ResultVO register( @RequestParam @Pattern(regexp = "^\\S{5,15}$") String username,
                             @RequestParam @Pattern(regexp = "^\\S{5,15}$") String password){
        System.out.println("=============");
        System.out.println(username);
        System.out.println(password);
        System.out.println("===========");
        // 判断是否已经有了该用户
        if (userService.findByName(username) != null)
            return ResultVO.error("该用户名已存在，请重试！");
        // 没有的话，继续注册
        userService.register(username, password);
        return ResultVO.success();
    }



    // 用户登录
    @PostMapping("/login")
    public ResultVO login(@RequestParam @Pattern(regexp = "^\\S{5,15}$") String username,
                          @RequestParam @Pattern(regexp = "^\\S{5,15}$") String password){
        // 判断用户是否存在
        User logUser = userService.findByName(username);
        if ( logUser == null) {
            return ResultVO.error("账户不存在");
        }else {
            // 存在，判断密码是否正确
            if (password.equals(logUser.getPassword())){
                // 登陆成功
                HashMap<String, Object> claims = new HashMap<>();
                claims.put("id", logUser.getId());
                claims.put("username", logUser.getUsername());
                String token = JwtUtils.genToken(claims);
                // 需要同时把token存到redis中
                ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
                operations.set(token,token,1, TimeUnit.DAYS);
                System.out.println(token);
                return ResultVO.success(token);
            }else {
                return ResultVO.error("密码不正确");
            }
        }
    }
    
//    // 登陆后获取用户信息
//    @GetMapping("/userInfo")
//    public ResultVO userInfo(@RequestHeader(name="Authorization") String token){
//        // 解析token
//        Map<String, Object> claims = JwtUtils.parseToken(token);
//        String username = (String) claims.get("username");
//        // 通过用户名查询用户信息
//        User user = userService.findByName(username);
//        return ResultVO.success(user);
//    }

    // 登陆后获取用户信息（优化版）
    @GetMapping("/userInfo")
    public ResultVO userInfo(){
        // 解析token
        Map<String, Object> claims = ThreadLocalUtils.get();
        String username = (String) claims.get("username");
        // 通过用户名查询用户信息
        User user = userService.findByName(username);
        System.out.println("====================================="+user);
        return ResultVO.success(user);
    }

    // 更新信息
    @PutMapping("/update")
    public ResultVO update(@RequestBody @Validated UserDTO userDTO){
        userService.update(userDTO);
        return ResultVO.success();
    }

    // 更新头像
    @PatchMapping("/updateAvatar")
    public ResultVO updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return ResultVO.success();
    }

    // 更新密码
    @PatchMapping("/updatePwd")
    public ResultVO updatePwd(@RequestBody Map<String,String> map, @RequestHeader("Authorization") String token){
        // 验证传入的密码
        String oldpwd = map.get("old_pwd");
        String newpwd = map.get("new_pwd");
        String repwd = map.get("re_pwd");
        if (!StringUtils.hasLength(oldpwd)
                || !StringUtils.hasLength(newpwd)
                || !StringUtils.hasLength(repwd)){
            ResultVO.error("缺少必要的参数！");
        }
        // 获取系统旧的密码进行验证
        Map claims = ThreadLocalUtils.get();
        String username = (String) claims.get("username");
        User loginUser = userService.findByName(username);
        if (!oldpwd.equals(loginUser.getPassword())){
           return ResultVO.error("旧密码输入不正确！");
        }
        // 两次输入密码是否一致
        if (!newpwd.equals(repwd))
           return ResultVO.error("新密码两次不一致，请重试");
       // 修改密码
        userService.updatePwd(newpwd,username);
        // 删除redis中的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return ResultVO.success();
    }
}
